/**
 * @file lv_port_disp_templ.c
 *
 */

/*Copy this file as "lv_port_disp.c" and set this value to "1" to enable content*/
#if 1

/*********************
 *      INCLUDES
 *********************/
#include "lv_port_disp_template.h"
#include "driver/gpio.h"
#include "driver/spi_master.h"
#include "st7789.h"
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

/*********************
 *      DEFINES
 *********************/
#ifndef MY_DISP_HOR_RES
// #warning Please define or replace the macro MY_DISP_HOR_RES with the actual screen width, default value 320 is used for now.
#define MY_DISP_HOR_RES 240
#endif

#ifndef MY_DISP_VER_RES
// #warning Please define or replace the macro MY_DISP_HOR_RES with the actual screen height, default value 240 is used for now.
#define MY_DISP_VER_RES 280
#endif

/**********************
 *      TYPEDEFS
 **********************/

/**********************
 *  STATIC PROTOTYPES
 **********************/
static void disp_init(void);

static void disp_flush(lv_disp_drv_t* disp_drv, const lv_area_t* area, lv_color_t* color_p);
// static void gpu_fill(lv_disp_drv_t * disp_drv, lv_color_t * dest_buf, lv_coord_t dest_width,
//         const lv_area_t * fill_area, lv_color_t color);

/**********************
 *  STATIC VARIABLES
 **********************/

/**********************
 *      MACROS
 **********************/

/**********************
 *   GLOBAL FUNCTIONS
 **********************/

void lv_port_disp_init(void)
{
	/*-------------------------
	 * Initialize your display
	 * -----------------------*/
	disp_init();

	/*-----------------------------
	 * Create a buffer for drawing
	 *----------------------------*/

	/**
	 * LVGL requires a buffer where it internally draws the widgets.
	 * Later this buffer will passed to your display driver's `flush_cb` to copy its content to your display.
	 * The buffer has to be greater than 1 display row
	 *
	 * There are 3 buffering configurations:
	 * 1. Create ONE buffer:
	 *      LVGL will draw the display's content here and writes it to your display
	 *
	 * 2. Create TWO buffer:
	 *      LVGL will draw the display's content to a buffer and writes it your display.
	 *      You should use DMA to write the buffer's content to the display.
	 *      It will enable LVGL to draw the next part of the screen to the other buffer while
	 *      the data is being sent form the first buffer. It makes rendering and flushing parallel.
	 *
	 * 3. Double buffering
	 *      Set 2 screens sized buffers and set disp_drv.full_refresh = 1.
	 *      This way LVGL will always provide the whole rendered screen in `flush_cb`
	 *      and you only need to change the frame buffer's address.
	 */

#if 0
	/* Example for 1) */
	static lv_disp_draw_buf_t draw_buf_dsc;
	static lv_color_t buf_1[MY_DISP_HOR_RES * 10];                             /*A buffer for 10 rows*/
	lv_disp_draw_buf_init(&draw_buf_dsc, buf_1, NULL, MY_DISP_HOR_RES * 10); /*Initialize the display buffer*/
#endif

#if 1
	/* Example for 2) */
	static lv_disp_draw_buf_t draw_buf_dsc;
	static lv_color_t buf_2_1[MY_DISP_HOR_RES * 40];                              /*A buffer for 10 rows*/
	static lv_color_t buf_2_2[MY_DISP_HOR_RES * 40];                              /*An other buffer for 10 rows*/
	lv_disp_draw_buf_init(&draw_buf_dsc, buf_2_1, buf_2_2, MY_DISP_HOR_RES * 40); /*Initialize the display buffer*/
#endif

#if 0
	/* Example for 3) also set disp_drv.full_refresh = 1 below*/
	static lv_disp_draw_buf_t draw_buf_dsc;
	static lv_color_t buf_3_1[MY_DISP_HOR_RES * MY_DISP_VER_RES];                              /*A screen sized buffer*/
	static lv_color_t buf_3_2[MY_DISP_HOR_RES * MY_DISP_VER_RES];                              /*Another screen sized buffer*/
	lv_disp_draw_buf_init(&draw_buf_dsc, buf_3_1, buf_3_2, MY_DISP_VER_RES * MY_DISP_HOR_RES); /*Initialize the display buffer*/
#endif

	/*-----------------------------------
	 * Register the display in LVGL
	 *----------------------------------*/

	static lv_disp_drv_t disp_drv; /*Descriptor of a display driver*/
	lv_disp_drv_init(&disp_drv);   /*Basic initialization*/

	/*Set up the functions to access to your display*/

	/*Set the resolution of the display*/
	disp_drv.hor_res = MY_DISP_HOR_RES;
	disp_drv.ver_res = MY_DISP_VER_RES;

	/*Used to copy the buffer's content to the display*/
	disp_drv.flush_cb = disp_flush;

	/*Set a display buffer*/
	disp_drv.draw_buf = &draw_buf_dsc;

	/*Required for Example 3)*/
	// disp_drv.full_refresh = 1;

	/* Fill a memory array with a color if you have GPU.
	 * Note that, in lv_conf.h you can enable GPUs that has built-in support in LVGL.
	 * But if you have a different GPU you can use with this callback.*/
	// disp_drv.gpu_fill_cb = gpu_fill;

	/*Finally register the driver*/
	lv_disp_drv_register(&disp_drv);
}

/**********************
 *   STATIC FUNCTIONS
 **********************/
#define ST7789_CLK_PIN  2
#define ST7789_MOSI_PIN 3
#define ST7789_CS_PIN   10
#define ST7789_RST_PIN  6
#define ST7789_DC_PIN   7
#define ST7789_BL_PIN   11

static spi_device_handle_t spi;

void esp32c3_spi_write(uint8_t* bytes, uint32_t len)
{
	uint32_t section = 4096;
	spi_transaction_t t;

	if (!len) {
		return;
	}

	while (len > section) {
		memset(&t, 0, sizeof(t));             // Zero out the transaction
		t.length = 8 * section;               // Command is 8 bits
		t.tx_buffer = bytes;                  // The data is the cmd itself
		spi_device_polling_transmit(spi, &t); // Transmit!
		bytes += section;
		len -= section;
	}

	memset(&t, 0, sizeof(t));             // Zero out the transaction
	t.length = 8 * len;                   // Command is 8 bits
	t.tx_buffer = bytes;                  // The data is the cmd itself
	spi_device_polling_transmit(spi, &t); // Transmit!
}

static void esp32c3_rst_pin(int val)
{
	gpio_set_level(ST7789_RST_PIN, val);
}

static void esp32c3_dc_pin(int val)
{
	gpio_set_level(ST7789_DC_PIN, val);
}

static void esp32c3_bl_pin(int val)
{
	gpio_set_level(ST7789_BL_PIN, val);
}

static void esp32c3_msleep(int ms)
{
	usleep(1000 * ms);
}

static void board_init()
{
	/* gpio */
	gpio_reset_pin(ST7789_RST_PIN);
	gpio_set_direction(ST7789_RST_PIN, GPIO_MODE_OUTPUT);

	gpio_reset_pin(ST7789_DC_PIN);
	gpio_set_direction(ST7789_DC_PIN, GPIO_MODE_OUTPUT);

	gpio_reset_pin(ST7789_BL_PIN);
	gpio_set_direction(ST7789_BL_PIN, GPIO_MODE_OUTPUT);

	spi_bus_config_t buscfg = {
		.miso_io_num = -1,
		.mosi_io_num = ST7789_MOSI_PIN,
		.sclk_io_num = ST7789_CLK_PIN,
		.quadwp_io_num = -1,
		.quadhd_io_num = -1,
		.max_transfer_sz = 4096,
	};

	spi_device_interface_config_t devcfg = {
		.clock_speed_hz = 80000000,    // SPI clk
		.mode = 0,                     // SPI mode
		.spics_io_num = ST7789_CS_PIN, // CS pin
		.queue_size = 7,               // We want to be able to queue 7 transactions at a time
	};

	spi_bus_initialize(SPI2_HOST, &buscfg, SPI_DMA_CH_AUTO);
	spi_bus_add_device(SPI2_HOST, &devcfg, &spi);
}

struct st7789 lcd;

/*Initialize your display and the required peripherals.*/
static void disp_init(void)
{
	/*You code here*/
	board_init();

	/* set lcd param */
	lcd.cfg.fix.width = 240;
	lcd.cfg.fix.height = 280;
	lcd.cfg.fix.xshift = 0;
	lcd.cfg.fix.yshift = 20;
	lcd.cfg.fix.bits = 8;
	lcd.cfg.var.orien = 0;

	/* register the operation */
	lcd.ops.reset = esp32c3_rst_pin;
	lcd.ops.datacmd = esp32c3_dc_pin;
	lcd.ops.backlight = esp32c3_bl_pin;
	lcd.ops.msleep = esp32c3_msleep;
	lcd.ops.write = esp32c3_spi_write;

	st7789_init(&lcd);
}

volatile bool disp_flush_enabled = true;

/* Enable updating the screen (the flushing process) when disp_flush() is called by LVGL
 */
void disp_enable_update(void)
{
	disp_flush_enabled = true;
}

/* Disable updating the screen (the flushing process) when disp_flush() is called by LVGL
 */
void disp_disable_update(void)
{
	disp_flush_enabled = false;
}

/*Flush the content of the internal buffer the specific area on the display
 *You can use DMA or any hardware acceleration to do this operation in the background but
 *'lv_disp_flush_ready()' has to be called when finished.*/
static void disp_flush(lv_disp_drv_t* disp_drv, const lv_area_t* area, lv_color_t* color_p)
{
	if (disp_flush_enabled) {
		/*The most simple case (but also the slowest) to put all pixels to the screen one-by-one*/
		st7789_rect_fill(&lcd, area->x1, area->y1, area->x2, area->y2, (uint16_t*)color_p);
	}

	/*IMPORTANT!!!
	 *Inform the graphics library that you are ready with the flushing*/
	lv_disp_flush_ready(disp_drv);
}

/*OPTIONAL: GPU INTERFACE*/

/*If your MCU has hardware accelerator (GPU) then you can use it to fill a memory with a color*/
// static void gpu_fill(lv_disp_drv_t * disp_drv, lv_color_t * dest_buf, lv_coord_t dest_width,
//                     const lv_area_t * fill_area, lv_color_t color)
//{
//     /*It's an example code which should be done by your GPU*/
//     int32_t x, y;
//     dest_buf += dest_width * fill_area->y1; /*Go to the first line*/
//
//     for(y = fill_area->y1; y <= fill_area->y2; y++) {
//         for(x = fill_area->x1; x <= fill_area->x2; x++) {
//             dest_buf[x] = color;
//         }
//         dest_buf+=dest_width;    /*Go to the next line*/
//     }
// }

#else /*Enable this file at the top*/

/*This dummy typedef exists purely to silence -Wpedantic.*/
typedef int keep_pedantic_happy;
#endif
